package com.fashion.service.gallery;

import com.fashion.model.gallery.RecommendPhoto;
import com.fashion.utils.StringUtils;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

/*import com.fashion.utils.Variable;*/

@Service("recommendPhotoService")
public class RecommendPhotoService {
    private static int PHOTO_SIZE = 550;
	@Resource(name = "hibernateTemplate")
	private HibernateTemplate template;
	
	public List<RecommendPhoto> findAll(){
	    return template.find("from RecommendPhoto order by date desc");
	}
	
	public void addRecommendPhoto(RecommendPhoto recommendPhoto){
	    recommendPhoto.setId(StringUtils.createGuid());
	    recommendPhoto.setDate(new Date());
        template.save(recommendPhoto);
    }
	
	public void updateRecommendPhoto(RecommendPhoto recommendPhoto){
	    recommendPhoto.setDate(new Date());
        template.update(recommendPhoto);
    }
	
	public void delRecommendPhoto(RecommendPhoto recommendPhoto){
        template.delete(recommendPhoto);
    }
	
	public void savePhoto(File file, String saveName, String saveFolder) throws Exception{
  /*      File folder = new File(saveFolder);
        if(!folder.exists()){
            folder.mkdir();
        }
        String dest = saveFolder + File.separator + saveName;
        savePhoto(file, PHOTO_SIZE, dest);*/
    }
	
	private void savePhoto (File file, int size, String dest)throws Exception{
        Image src = javax.imageio.ImageIO.read(file);
        int oldWidth = src.getWidth(null);
        int oldHeight = src.getHeight(null);
        int newWidth = 0;
        int newHeight = 0;
        if (oldWidth < size && oldHeight < size) {
            return;
        }

        if (oldWidth > oldHeight) {

            newWidth = Math.round(size);
            float scale = size / (float)oldWidth;
            newHeight = Math.round(scale * oldHeight);
        } else {
            newHeight = Math.round(size);
            float scale = size / (float)oldHeight;
            newWidth = Math.round(scale * oldWidth);

        }

        BufferedImage tag = new BufferedImage(newWidth, newHeight,
                BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(src, 0, 0, newWidth, newHeight, null);
        FileOutputStream newimage = new FileOutputStream(dest);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
        encoder.encode(tag);
        newimage.close();
    }
}
